import java.util.LinkedList;
import java.util.List;

/**
 * Simple Random AI Player
 * 
 * This guy just finds all the possible locations his tile can go,
 * then chooses one at random. He also places a meeple at random.
 * 
 * @author ben
 */
public class AIPlayer extends Player {

	public AIPlayer(String name, int colour, Game g)
	{
		super(name,colour,g);
	}
	
	public void playTurn(Tile t) throws InterruptedException
	{ 
		LinkedList<Board.Location> validLocations = new LinkedList<Board.Location>();
		for(int i=0;i<game.board.height;i++)
		{
			for(int j=0;j<game.board.width;j++)
			{
				// try all rotations..
				for(int r=0;r<4;r++)
				{
					t.rotate();
					if (game.board.isValidLocation(i, j, t))
					{
						validLocations.add(new Board.Location(i,j));
						break; // don't try other rotations...
					}
				}				
			}
		}
		
		// skip turn if we can't place the tile...
		if (validLocations.isEmpty())
		{
			game.skipTile();
			return;
		}
		
		// choose a random valid location
		Board.Location l = validLocations.get((int)(Math.random()*validLocations.size()));
		// find a rotation that fits...
		int r = 0;
		for(;r<4;r++)
		{
			t.rotate();
			if (game.board.isValidLocation(l.i,l.j,t)) break;			
		}
		if (r==4)
		{
			System.out.println("ERROR!");
			System.exit(1);
		}
		
		// just pause for a tiny bit...
		Thread.currentThread().sleep(100);
		
		// else, place the tile and check for valid meeple locations...
		game.placeTile(t, l.i, l.j);
		
		// choose a random meeple location...
		LinkedList<Tile.MeepleLocation> validMLs = new LinkedList<Tile.MeepleLocation>(); 
		for (Tile.MeepleLocation ml: t.meeple_locations)
		{
			if (game.canPlaceMeeple(ml))
				validMLs.add(ml);
		}
		
		if (!validMLs.isEmpty() && this.hasUnplayedMeeples())
		{
			game.placeMeeple(validMLs.get((int)(Math.random()*validMLs.size())));
		}
		else
		{
			game.skipMeeple();
		}
	}
}
